package UserAdapter;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.talksdk.R;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import UserGlobal.GlobalData;

public class FriendsAdapter extends RecyclerView.Adapter<FriendsAdapter.ViewHolder> {
    ItemOnClickListener mItemOnClickListener = null;

    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView mTextView, mHintTextView;

        public ViewHolder(View itemView) {
            super(itemView);
            mTextView = itemView.findViewById(R.id.iditem);
            mHintTextView = itemView.findViewById(R.id.itemhinttext);
        }
    }

    public interface ItemOnClickListener {
        void onclick(ViewHolder view, int postion);
    }

    public void setmItemOnClickListener(ItemOnClickListener itemOnClickListener) {
        this.mItemOnClickListener = itemOnClickListener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.frienditem, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        String id = GlobalData.idlist.get(position);
        holder.mTextView.setText(id);
        holder.mHintTextView.setText("");
        int index = GlobalData.mHistoryId.indexOf(id);
        if (index != -1){
            if(GlobalData.mChatHistory.get(index).size()!= 0) {
                ArrayList<Map<Integer, String>> mGravityList = GlobalData.mChatHistory.get(index);
                int len = mGravityList.size();
                Set set = mGravityList.get(len - 1).entrySet();
                Iterator iterator = set.iterator();
                Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>) iterator.next();
                if (entry.getKey() == Gravity.RIGHT)
                    holder.mHintTextView.setText("you:" + entry.getValue());
                else
                    holder.mHintTextView.setText(id+":" + entry.getValue());
            }
        }
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mItemOnClickListener != null)
                    mItemOnClickListener.onclick(holder, position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return GlobalData.idlist.size();
    }
}
